package com.mk.legoscans2.data;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.os.Environment;

public class SdCardFileService {
	
	private String _path;
	public SdCardFileService(String path)
	{
		_path = path;
		
		File dir = new File(_path);
        if (!dir.exists())
        {
        	dir.mkdirs(); 
        }
	}
	
	public boolean IsSdCardMounted()
	{
		String extState = Environment.getExternalStorageState();
		return extState.equals(Environment.MEDIA_MOUNTED);
	}
	
	
	public boolean Store(String folderName, String fileName, boolean deleteOldData, byte[] data) 
	{
		if( !IsSdCardMounted() )
		{
			return false;
		}
		
		File scanDirectory = new File(_path + folderName);
		if(deleteOldData)
		{
			//if the directory already exist
			if (scanDirectory.exists())
	        {
				//get the list of files that is contained within the directory
	        	File[] files = scanDirectory.listFiles();
	        	for (File file : files) {
					//abort if file can not be deleted
					if(!file.delete())
					{
						return false;
					}
				}
	        	
	        	//abort if directory can not be deleted
	        	if(!scanDirectory.delete())
	        	{
	        		return false;
	        	}
	        }
		}
        
		//abort if directory can not be created
		if(!scanDirectory.exists())
		{
			boolean success = scanDirectory.mkdirs();
			if(!success)
	        {
	        	return false;
	        }	
		}
        
		try 
		{
            FileOutputStream fileOutputStream = new FileOutputStream( scanDirectory.getAbsolutePath() + "/" + fileName);
            fileOutputStream.write(data);

            fileOutputStream.flush();
            fileOutputStream.close();
        }
		catch (IOException ioe) 
        {
            return false;
        }
		
		return true;
	}
}
